package com.xdf.ecommerce.service.hystrix;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixRequestCache;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault;
import com.xdf.ecommerce.service.NacosClientService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;

import java.util.Collections;
import java.util.List;

/**
 * @author chanchaw
 * @create 2025-10-30 14:42
 */
@Slf4j
public class CacheHystrixCommand extends HystrixCommand<List<ServiceInstance>> {
    private NacosClientService service;// 需要被保护的服务
    private String serviceId;// 服务名称
    private static final HystrixCommandKey CACHED_KEY = HystrixCommandKey.Factory.asKey("CacheHystrixCommand");
    public CacheHystrixCommand(NacosClientService service, String serviceId){
        super(
                HystrixCommand.Setter
                        .withGroupKey(HystrixCommandGroupKey
                                .Factory.asKey("CacheHystrixCommandGroup"))
                        .andCommandKey(CACHED_KEY)
        );
        this.service = service;
        this.serviceId = serviceId;
    }
    protected CacheHystrixCommand(HystrixCommandGroupKey group) {
        super(group);
    }

    @Override
    protected List<ServiceInstance> run() throws Exception {
        log.info("优先从缓存中获取服务实例，服务id：[{}]，线程名称：[{}]", this.serviceId,Thread.currentThread().getName());
        return this.service.getNacosClientInfo(this.serviceId);
    }

    @Override
    protected String getCacheKey() {
        return this.serviceId;
    }

    @Override
    protected List<ServiceInstance> getFallback() {
        log.warn("优先从缓存中查询获取服务实例的请求被降级处理，返回空数据");
        return Collections.emptyList();
    }

    public static void flushCache(String serviceId){
        HystrixRequestCache.getInstance(CACHED_KEY, HystrixConcurrencyStrategyDefault.getInstance()).clear(serviceId);
        log.info("已清理 Hystrix 请求缓存，服务id:[{}]，线程名称：[{}]", serviceId, Thread.currentThread().getName());
    }
}
